function modulated_symbols = modulate_qam(bits, modulation_type)
% modulate_qam - 对输入比特进行QAM调制
%
% 输入参数:
%   bits - 输入的比特流
%   modulation_type - 调制类型: 'BPSK', 'QPSK', 'QAM16', 'QAM64'
%
% 输出参数:
%   modulated_symbols - 调制后的复符号

% 确定每个符号包含的比特数
bits_per_symbol = get_bits_per_symbol(modulation_type);

% 确保比特数是调制阶数的整数倍
num_bits = length(bits);
if mod(num_bits, bits_per_symbol) ~= 0
    padding = bits_per_symbol - mod(num_bits, bits_per_symbol);
    bits = [bits; zeros(padding, 1)];
    warning('比特数不是调制阶数的整数倍，已在末尾填充%d个0', padding);
    num_bits = length(bits);
end

% 计算符号数量
num_symbols = num_bits / bits_per_symbol;

% 初始化调制符号
modulated_symbols = zeros(num_symbols, 1);

switch upper(modulation_type)
    case 'BPSK'
        % BPSK调制: 0 -> -1, 1 -> 1
        modulated_symbols = 2 * bits - 1;
        
    case 'QPSK'
        % QPSK调制
        % 处理比特流，每2比特映射为一个复符号
        for i = 1:num_symbols
            bit_idx = (i-1)*2 + 1;
            symbol_bits = bits(bit_idx:bit_idx+1);
            
            % 根据 Gray 码映射
            % 00 -> -1-1i, 01 -> -1+1i, 10 -> 1-1i, 11 -> 1+1i
            I = 2*symbol_bits(1) - 1;  % 第一位决定实部
            Q = 2*symbol_bits(2) - 1;  % 第二位决定虚部
            
            % 构造复符号并归一化能量
            modulated_symbols(i) = (I + 1i*Q) / sqrt(2);
        end
        
    case 'QAM16'
        % 16QAM调制
        % 处理比特流，每4比特映射为一个复符号
        for i = 1:num_symbols
            bit_idx = (i-1)*4 + 1;
            symbol_bits = bits(bit_idx:bit_idx+3);
            
            % 对实部和虚部分别做 Gray 码映射
            % 使用前两位确定实部，后两位确定虚部
            I_bits = symbol_bits(1:2);
            Q_bits = symbol_bits(3:4);
            
            % 映射实部: 00 -> -3, 01 -> -1, 11 -> 1, 10 -> 3
            if I_bits(1) == 0
                I = -3 + 2*(I_bits(2));
            else
                I = 1 - 2*(I_bits(2));
            end
            
            % 映射虚部: 00 -> -3, 01 -> -1, 11 -> 1, 10 -> 3
            if Q_bits(1) == 0
                Q = -3 + 2*(Q_bits(2));
            else
                Q = 1 - 2*(Q_bits(2));
            end
            
            % 构造复符号并归一化能量
            modulated_symbols(i) = (I + 1i*Q) / sqrt(10);
        end
        
    case 'QAM64'
        % 64QAM调制
        % 处理比特流，每6比特映射为一个复符号
        for i = 1:num_symbols
            bit_idx = (i-1)*6 + 1;
            symbol_bits = bits(bit_idx:bit_idx+5);
            
            % 前3位确定实部，后3位确定虚部
            I_bits = symbol_bits(1:3);
            Q_bits = symbol_bits(4:6);
            
            % 映射实部（采用Gray码）
            I_val = bin2dec(char(I_bits' + '0'));
            I = 2*(I_val) - 7;  % 映射到 -7, -5, -3, -1, 1, 3, 5, 7
            
            % 映射虚部（采用Gray码）
            Q_val = bin2dec(char(Q_bits' + '0'));
            Q = 2*(Q_val) - 7;  % 映射到 -7, -5, -3, -1, 1, 3, 5, 7
            
            % 构造复符号并归一化能量
            modulated_symbols(i) = (I + 1i*Q) / sqrt(42);
        end
        
    otherwise
        error('不支持的调制类型: %s', modulation_type);
end

end 